
#region Imports

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace Justa.Data.Active
{
    /// <summary>
    /// 
    /// </summary>
    /// 
    /// <typeparam name="T"></typeparam>
    /// 
    public class EntityDataAccess<T> : GenericDataAccess
    {
        /// <summary>
        /// 
        /// </summary>
        /// 
        /// <param name="database"></param>
        /// 
        public EntityDataAccess(string database) :
            base(database)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// 
        /// <param name="entity"></param>
        /// 
        /// <returns></returns>
        /// 
        public T SimpleSelect(AbstractEntity<T> entity)
        {
            T result = default(T);

            try
            {
                using (System.Data.IDataReader reader = GetQueryDataReader("select * from..."))
                {
                    result = GetEntity(reader, entity);
                }
            }
            catch (Exception exception)
            {
                DataAccessExceptionHandler.Process(exception, "Failed to get {0} by Id.", typeof(T));
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// 
        /// <param name="reader"></param>
        /// <param name="entity"></param>
        /// 
        /// <returns></returns>
        /// 
        public T GetEntity(System.Data.IDataReader reader, AbstractEntity<T> entity)
        {
            if (reader == null || entity == null)
            {
                DataAccessExceptionHandler.Process(null, "Failed to find single entity (reader/rowMapper is null).");
            }

            while (reader.Read())
            {
                return entity.GetEntity(reader);
            }

            DataAccessExceptionHandler.Process(null, "Failed to find single entity from reader.");
            return default(T);
        }
    }
}